package solutions.ferpa.ztest.intf;

import br.com.telescope.adsrt.dom.DomTextHtml;
import br.com.telescope.adsrt.lib.*;
import br.com.telescope.sql.DataBaseSchemaManager;
import br.com.telescope.t2.ServiceModel;
import br.com.telescope.t2.ServiceUrlManager;
import br.com.telescope.t2.exception.ApplicationRuntimeException;
import br.com.telescope.t2.feature.AbstractFeature;
import br.com.telescope.t2.feature.CustomFeature;
import solutions.ferpa.ztest.ent.*;

/**
 * Rotinas de atualização.
 * <p>
 * Apresenta e executa rotinas de atualização pendentes.
 * <P>
 * Telescope origin: RTSYSINF.PRO_ATUALIZACOES
 * <P>
 * @author TELESCOPE - Build task T2 Web Interface Generator
 * <P>
 * @version 0.1
 */
public class ProAtualizacoes extends ServiceModel {
    
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    public static final String GLOBAL_NAME = "RTSYSINF.PRO_ATUALIZACOES";
    
    @Override
    public String globalName() {
        return GLOBAL_NAME;
    }
    
    {
        setTitle("Rotinas de atualização");
    }
    
    
    // Record items
    private DomTextHtml aResultado;
    
    // Query items
    
    @Override
    public void initAttributes() {
        
        aResultado = new DomTextHtml();
        aResultado.context(ctx).name("RESULTADO").label("Resultado").unbound(true);
        
    }
    
    @Override
    public String getDefaultOrderBy() {
        return "";
    }
    // </editor-fold>
    
    // <editor-fold defaultstate="collapsed" desc="EXECUTAR">
    public class FExecutar extends CustomFeature {
        
        @Override
        public void initForm() {
            aResultado.setEditable(false);
            addField(aResultado, "view");
        }
        
        @Override
        public void execute() {
            try {
                executar();
            } catch (AdsException ex) {
                throw new ApplicationRuntimeException(ex);
            }
        }
        
        {
            setFeatureName("EXECUTAR");
            setTitle("Executar");
            setPrimary(false);
        }
    }
    // </editor-fold>
    
    // <editor-fold defaultstate="collapsed" desc="initFeatures">
    
    @Override
    protected void initFeatures() {
        addFeature(new FExecutar());
        super.initFeatures();
    }
    
    @Override
    public String getDefaultFeature() {
        return "EXECUTAR";
    }
    // </editor-fold>
    
    // <editor-fold defaultstate="collapsed" desc="Getters and Setters">
    
    public String getResultado() {
        return aResultado.getValue();
    }
    
    public void setResultado(String value) {
        this.aResultado.setValue(value);
    }
    // </editor-fold>
    
    /**
     * Executar.
     */
    public void executar() throws AdsException {
        // <user-code id="20738544" parentId="20738541" hashcode="-4eaf94b5" length="2099">
        // import br.com.telescope.t2.ServiceModel;
        // import br.com.telescope.t2.ServiceUrlManager;
        // import br.com.telescope.t2.feature.AbstractFeature;
        // import br.com.telescope.sql.DataBaseSchemaManager;
        DataBaseSchemaManager schema = new DataBaseSchemaManager(ctx);
        schema.updateSchema(1); 
        ServiceUrlManager manager = ServiceUrlManager.getInstance();
        EntOperacoesSistemas upgrade = new EntOperacoesSistemas(ctx);
        StringBuilder message = new StringBuilder(upgrade.atualizar());
        upgrade.filterBy()
                .like(upgrade.getOperacao(), "%.UPGRADE%")
                .equal(upgrade.getSituacao(), "A");
        upgrade.orderBy().asc(upgrade.getOperacao());
        String title = null;
        while (upgrade.next()) {
            try {
                title = upgrade.valueOfOperacao();
                String[] parts = title.split("\\.");
                if (parts.length == 3) {
                    String serviceName = parts[0] + "." + parts[1];
                    String featureName = parts[2];
                    Class<ServiceModel> serviceClass = manager.getClassForService(serviceName);
                    ServiceModel service = serviceClass.newInstance();
                    service.instantiate(ctx);
                    AbstractFeature feature = service.getFeature(featureName);
                    title = service.getTitle() + " - " + feature.getTitle();
                    boolean temForm = feature.getForm().size() > 0;
                    if (temForm) {
                        String uri = manager.getUriForService(upgrade.valueOfOperacao());
                        message.append("- ").append(title)
                                .append(" - Clique <a href=\"")
                                .append(uri)
                                .append("\">aqui</a>");
                    } else {
                        feature.run();
                        message.append("OK - ").append(title);
                    }
                }
            } catch (Exception ex) {
                message.append("ERROR - ").append(title).append(": ").append(ex.getMessage());
            }
            message.append("<br>");
        }
        if (message.length() > 0) {
            aResultado.setValue(message.toString());
        } else {
            aResultado.setValue("Nenhuma rotina de atualização pendente encontrada!");
        }
        // </user-code>
    }
}
